package com.hhu.commonutils.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonUtil {
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * create by: yaodao
     * description: 将json串转为相应类型的对象
     * create time: 2021/12/11 12:36 下午
     */
    public static <T> T jsonToObject(String jsonData, Class<T> classType) {
        try {
            T t = MAPPER.readValue(jsonData, classType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * create by: yaodao
     * description: 对象转json
     * create time: 2021/12/11 12:39 下午
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * create by: yaodao
     * description: 转成json后再转为新对象
     * create time: 2021/12/11 12:40 下午
     */
    public static <T> T getNewObject(Object oldObject, Class<T> classType) {
        return jsonToObject(objectToJson(oldObject), classType);
    }
}
